Skip to main content

5_1. Functions

Basic Function

fn greet() {
println!("Hello!");
}

Function with Parameters

fn add(a: i32, b: i32) {
println!("{}", a + b);
}

fn greet(name: &str) {
println!("Hello, {}!", name);
}
PartMeaning
nameParameter name
&strParameter type (string slice)

Function with Return Value

fn multiply(a: i32, b: i32) -> i32 {
a * b // no semicolon → return value
}
  • No semicolon (;) at the end
SyntaxMeaning
-> i32Return type
no returnLast expression is returned

With return Keyword (Optional)

fn square(x: i32) -> i32 {
return x * x;
}

Both are valid, but the expression style is preferred.

Statements vs Expressions in Functions

fn calculate() -> i32 {
let x = 5; // statement
x + 1 // expression → returned
}

This would be wrong:

x + 1; // semicolon removes return value

Function with Conditional Return

fn check_age(age: u8) -> &'static str {
if age >= 18 {
"Adult"
} else {
"Minor"
}
}
  • if is an expression
  • Both branches return the same type

Functions and Ownership (Intro Example)

fn take_ownership(s: String) {
println!("{}", s);
}

fn main() {
let name = String::from("Rust");
take_ownership(name);

// println!("{}", name); ❌ error
}

Ownership moves into the function.

Borrowing Instead

fn borrow_string(s: &String) {
println!("{}", s);
}

fn main() {
let name = String::from("Rust");
borrow_string(&name);
println!("{}", name); // ✅ still valid
}

Mutable Parameters

fn add_exclamation(s: &mut String) {
s.push('!');
}

fn main() {
let mut text = String::from("Hello");
add_exclamation(&mut text);
println!("{}", text);
}

Functions Returning Ownership

fn create_message() -> String {
String::from("Hello, Rust")
}

Usage:

let msg = create_message();

Functions with Tuples (Multiple Values)

Rust functions return only one value, but that value can be a tuple.

fn calculate(x: i32, y: i32) -> (i32, i32) {
(x + y, x * y)
}

Usage:

let (sum, product) = calculate(3, 4);

Early Return Example

fn divide(a: i32, b: i32) -> i32 {
if b == 0 {
return 0;
}
a / b
}

Full Example Program

fn greet(name: &str) {
println!("Hello, {}!", name);
}

fn square(n: i32) -> i32 {
n * n
}

fn main() {
greet("Alice");

let result = square(4);
println!("Square = {}", result);
}